﻿using Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Model.ModelForJD;

/// <summary>
/// DataInteractForJD 的摘要说明
/// </summary>
public static class DataInteractForJD
{

    #region 京东交互方法
    /// <summary>
    /// 请求京东接口
    /// </summary>
    /// <typeparam name="T">返回相应类实体</typeparam>
    /// <param name="url">请求地址</param>
    /// <param name="key">请求形参例：token=3，传入token</param>
    /// <param name="value">请求实参例：token=3，传入3</param>
    public static T GetData<T>(string url, List<string> key, List<string> value)
    {
        StringBuilder urls = new StringBuilder();
        urls.Append(url + "?");
        for (int i = 0; i < key.Count; i++)
        {
            urls.Append(key[i] + "=" + value[i] + "&");
        }
        //去掉最后的字符&
        string ul = urls.ToString().Substring(0, urls.ToString().Length - 1);
        WebRequest request = WebRequest.Create(ul);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        JavaScriptSerializer jsonReader = new JavaScriptSerializer();
        return jsonReader.Deserialize<T>(strMsg);
    }
    #endregion

    #region 获取京东Token
    /// <summary>
    /// 返回京东交互Token码
    /// </summary>
    /// <returns></returns>
    public static string GetJdToken()
    {
        #region 初始化参数值
        string username = "债无忧";
        string password = EncryptUtil.Md5Encode("111000");
        string grant_type = "access_token";
        string client_id = "6OfiBOh8VBCvC2cuMH9J";
        string client_secret = "P3fVQ5g2VED9iqiux441";
        string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        #endregion
        //拼接标识（使用MD5加密）
        string sign = EncryptUtil.Md5ForJd(client_secret + timestamp + client_id + username + password + grant_type + client_secret).ToUpper();
        //请求地址
        string url = "https://bizapi.jd.com/oauth2/accessToken";
        //请求形参集合
        List<string> ls = new List<string> { "grant_type", "client_id", "username", "password", "timestamp", "sign" };
        //请求实参集合
        List<string> list = new List<string> { grant_type, client_id, HttpUtility.UrlEncode(username, Encoding.UTF8), password, timestamp, sign };
        TokenForJD model = DataInteractForJD.GetData<TokenForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 获取商品池编号
    /// <summary>
    /// 获取商品池编号
    /// </summary>
    /// <param name="token">token码</param>
    public static string GetGoodsPool(string token)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/product/getPageNum";
        //请求形参集合
        List<string> ls = new List<string> { "token" };
        //请求实参集合
        List<string> list = new List<string> { token };
        GoodsPoolForJD model = DataInteractForJD.GetData<GoodsPoolForJD>(url, ls, list);

        
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 获取商品池内商品编号
    /// <summary>
    /// 京东获取商品池内商品编号
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="page_num">商品池编号</param>
    public static string GetGoodsForJD(string token, string page_num)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/product/getSku";
        //请求形参集合
        List<string> ls = new List<string> { "token", "pageNum" };
        //请求实参集合
        List<string> list = new List<string> { token, page_num };
        GoodsNumForJD model = DataInteractForJD.GetData<GoodsNumForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 获取商品池内商品
    /// <summary>
    /// 获取商品池内商品
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="sku">商品编号</param>
    /// <param name="is_show">是否了解详情true了解,false不了解</param>
    /// <returns>object[0]=0代表图书，1代表音像，2其他</returns>
    public static string GetGoods(string token,string sku,string is_show="false")
    {
        JavaScriptSerializer jsonReader = new JavaScriptSerializer();
        object[] obj = new object[2];
        //请求地址
        string url =string.Format("https://bizapi.jd.com/api/product/getDetail?token={0}&sku={1}&isShow={2}",token,sku,is_show);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        if (sku.Length == 8)
        {
            JObject o = JObject.Parse(strMsg);
            if (o["result"]["skuType"].ToString() == "book")
            {
                obj[0] = 0;
                obj[1] = jsonReader.Deserialize<GoodsTypeOneForJD>(strMsg);
            }
            else
            {
                obj[0] = 1;
                obj[1] = jsonReader.Deserialize<GoodsTypeTwoForJD>(strMsg);
            }
        }
        else
        {
            obj[0] = 2;
            obj[1] = jsonReader.Deserialize<GoodsTypeThreeForJD>(strMsg);
        }
        return JsonConvert.SerializeObject(obj); 
    }
    #endregion

    #region 获取商品上下架状态
    /// <summary>
    /// 获取商品上下架状态
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="sku">商品编号</param>
    /// <returns></returns>
    public static string GetGoodsSkuState(string token, string sku)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/product/skuState";
        //请求形参集合
        List<string> ls = new List<string> { "token", "sku" };
        //请求实参集合
        List<string> list = new List<string> { token, sku };
        GoodsSkuStateForJD model = DataInteractForJD.GetData<GoodsSkuStateForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 获取所有图片信息
    /// <summary>
    /// 返回所有图片信息集合
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="sku">商品编号（单次查询编号最多为100个）</param>
    /// <returns></returns>
    public static string GetSkuImage(string token, List<string> sku)
    {
        if (sku.Count > 100)
        {
            Common.GetInstance.JsonErrorMessage("商品编号数量不能大于100");
            return null;
        }
        SkuImageForJD model = new SkuImageForJD();
        JavaScriptSerializer jsonReader = new JavaScriptSerializer();
        string skuIds = string.Empty;
        foreach (string s in sku)
        {
            skuIds += s + ",";
        }
        skuIds = skuIds.Substring(0, skuIds.Length - 1);
        List<SkuImageDetilsForJD> ls = new List<SkuImageDetilsForJD>();
        //请求地址
        string url = string.Format("https://bizapi.jd.com/api/product/skuImage?token={0}&sku={1}",token,skuIds);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        JObject o = JObject.Parse(strMsg);
        if (Convert.ToBoolean(o["success"]))
        {
            foreach (string s in sku)
            {
                if (o["result"][s].ToString().Length > 0)
                {
                    for (int i = 0; i < o["result"][s].Count(); i++)
                    {
                        //SkuImageDetilsForJD model = new SkuImageDetilsForJD();
                        //model.id = o["result"][s][i]["id"].ToString();
                        //model.type = Convert.ToInt32(o["result"][s][i]["type"]);
                        //model.path = o["result"][s][i]["path"].ToString();
                        //model.position = o["result"][s][i]["position"].ToString();
                        //model.orderSort = Convert.ToInt32(o["result"][s][i]["orderSort"]);
                        //model.modified = Convert.ToDateTime(o["result"][s][i]["modified"]);
                        //model.created = Convert.ToDateTime(o["result"][s][i]["created"]);
                        //model.features = o["result"][s][i]["position"].ToString();
                        //model.isPrimary = Convert.ToInt32(o["result"][s][i]["isPrimary"]);
                        //model.skuId = o["result"][s][i]["skuId"].ToString();
                        //ls.Add(jsonReader.Deserialize<SkuImageDetilsForJD>(o["result"][s].ToString()));
                        ls.Add(jsonReader.Deserialize<SkuImageDetilsForJD>(o["result"][s][i].ToString()));
                    }
                }
            }
        }
        model.success = Convert.ToBoolean(o["success"]);
        model.resultMessage = o["resultMessage"].ToString();
        model.resultCode= o["resultCode"].ToString();
        model.result = ls;
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 商品区域购买限制查询
    /// <summary>
    /// 商品区域购买限制查询
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="skuIds">商品编号集合</param>
    /// <param name="province">省份</param>
    /// <param name="city">市区</param>
    /// <param name="county">县区</param>
    /// <param name="town">乡镇</param>
    /// <returns></returns>
    public static string GetCheckAreaLimit(string token, List<string> skuIds, string province, string city, string county, string town)
    {
        if (skuIds.Count > 100)
        {
            Common.GetInstance.JsonErrorMessage("商品编号数量不能大于100");
            return null;
        }
        string skuId = string.Empty;
        foreach (string s in skuIds)
        {
            skuId += s + ",";
        }
        skuId = skuId.Substring(0, skuId.Length - 1);
        
        string url = string.Format("https://bizapi.jd.com/api/product/checkAreaLimit?token={0}&skuIds={1}&province={2}&city={3}&county={4}&town={5}", token, skuId, province, city, county, town);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        JObject o = JObject.Parse(strMsg);
        //读取json:o节点下的result不规则json并转成为标准格式的json
        string json = "{result:" + o["result"].ToString().Replace(@"\", "") + "}";
        //序列为一个字典
        Dictionary<string, List<GoodsCheckAreaLimitDetailsForJD>> ls = new JavaScriptSerializer().Deserialize<Dictionary<string, List<GoodsCheckAreaLimitDetailsForJD>>>(json);

        GoodsCheckAreaLimitForJD model = new GoodsCheckAreaLimitForJD();
        model.success = Convert.ToBoolean(o["success"]);
        model.resultMessage = o["resultMessage"].ToString();
        model.resultCode = o["resultCode"].ToString();
        //读取key下的list集合
        model.result = ls["result"];
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 京东运费查询接口 未测试
    public static string GetFreight(string token,List<string> sku,string province,string city,string county,string town,string paymentType)
    {
        if (sku.Count > 50)
        {
            Common.GetInstance.JsonErrorMessage("商品编号数量不能大于50");
            return null;
        }
        string skuId = "[";
        foreach (var item in sku)
        {
            skuId += item + ",";
        }
        skuId = skuId.Substring(0, skuId.Length - 1);
        skuId += "]";
        //请求地址
        string url = "https://bizapi.jd.com/api/order/getFreight";
        //请求形参集合
        List<string> ls = new List<string> { "token", "sku", "province", "city", "county", "town", "paymentType" };
        //请求实参集合
        List<string> list = new List<string> { token, skuId, province, city, county, town , paymentType };
        GetFreightForJD model=DataInteractForJD.GetData<GetFreightForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 商品可售验证接口
    /// <summary>
    /// 商品可售验证接口
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="skuIds">商品编号集合</param>
    /// <returns></returns>

    public static string GetGoodsCheck(string token, List<string> skuIds)
    {
        if (skuIds.Count > 100)
        {
            Common.GetInstance.JsonErrorMessage("商品编号数量不能大于100");
            return null;
        }
        string sku = string.Empty;
        foreach (string s in skuIds)
        {
            sku += s + ",";
        }
        sku = sku.Substring(0, sku.Length - 1);
        //请求地址
        string url = "http://bizapi.jd.com/api/product/check";
        //请求形参集合
        List<string> ls = new List<string> { "token", "skuIds" };
        //请求实参集合
        List<string> list = new List<string> { token, sku };
        GoodsCheckForJD model = DataInteractForJD.GetData<GoodsCheckForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 查询分类信息接口
    /// <summary>
    /// 查询分类信息接口
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="cid">商品分类ID</param>
    /// <returns></returns>

    public static string GetCategory(string token, string cid)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/product/getCategory";
        //请求形参集合
        List<string> ls = new List<string> { "token", "cid" };
        //请求实参集合
        List<string> list = new List<string> { token, cid };
        GoodsCategoryForJD model = DataInteractForJD.GetData<GoodsCategoryForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 查询分类列表信息接口
    /// <summary>
    /// 查询分类列表信息接口
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="pageNo">页号，从1开始</param>
    /// <param name="pageSize">页大小，最大值5000</param>
    /// <param name="parentId">父ID</param>
    /// <param name="catClass">分类等级（0:一级； 1:二级；2：三级）</param>
    /// <returns></returns>
    public static string GetCategorys(string token, string pageNo, string pageSize, string parentId ="", string catClass="")
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/product/getCategorys";
        //请求形参集合
        List<string> ls = new List<string> { "token", "pageNo", "pageSize", };
        //请求实参集合
        List<string> list = new List<string> { token, pageNo, pageSize };
        if (parentId.Trim().Length > 0)
        {
            ls.Add("parentId");
            list.Add(parentId);
        }
        if (catClass.Trim().Length > 0)
        {
            ls.Add("catClass");
            list.Add(catClass);
        }
        GoodsCategorysForJD model = DataInteractForJD.GetData<GoodsCategorysForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);

    }
    #endregion

    #region 同类商品查询
    /// <summary>
    /// 同类商品查询
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="skuId">商品编号</param>
    public static string GetSimilarSku(string token, string skuId)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/product/getSimilarSku";
        //请求形参集合
        List<string> ls = new List<string> { "token", "skuId" };
        //请求实参集合
        List<string> list = new List<string> { token, skuId };
        GoodsSimilarSkuForJD model = DataInteractForJD.GetData<GoodsSimilarSkuForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);

    }
    #endregion

    #region 获取一级地址
    /// <summary>
    /// 获取一级地址
    /// </summary>
    /// <param name="token">token码</param>
    /// <returns></returns>
    public static string GetProvince(string token)
    {
        ProvinceForJD model = new ProvinceForJD();
        List<ProvinceDetailsForJD> list = new List<ProvinceDetailsForJD>();
        //请求地址
        string url = string.Format("https://bizapi.jd.com/api/area/getProvince?token={0}", token);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        JObject o = JObject.Parse(strMsg);
        if (Convert.ToBoolean(o["success"]))
        {
            //json序列化成字典
            Dictionary<string, object> dict = serializer.Deserialize<Dictionary<string, object>>(o["result"].ToString());
            foreach (string s in dict.Keys)
            {
                list.Add(new ProvinceDetailsForJD { provinceId = Convert.ToInt32(dict[s]), provinceName = s });
            }
        }
        model.resultCode = o["success"].ToString();
        model.resultMessage = o["resultMessage"].ToString();
        model.success = Convert.ToBoolean(o["success"]);
        model.result = list;
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 获取二级地址
    /// <summary>
    /// 获取二级地址
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="id">一级地址ID</param>
    /// <returns></returns>
    public static string GetCity(string token,string id)
    {
        CityForJD model = new CityForJD();
        List<CityDetailsForJD> list = new List<CityDetailsForJD>();
        //请求地址
        string url = string.Format("https://bizapi.jd.com/api/area/getCity?token={0}&id={1}", token,id);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        JObject o = JObject.Parse(strMsg);
        if (Convert.ToBoolean(o["success"]))
        {
            //json序列化成字典
            Dictionary<string, object> dict = serializer.Deserialize<Dictionary<string, object>>(o["result"].ToString());
            foreach (string s in dict.Keys)
            {
                list.Add(new CityDetailsForJD { cityId = Convert.ToInt32(dict[s]), cityName = s });
            }
        }
        model.resultCode = o["success"].ToString();
        model.resultMessage = o["resultMessage"].ToString();
        model.success = Convert.ToBoolean(o["success"]);
        model.result = list;
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 获取三级地址
    /// <summary>
    /// 获取三级地址
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="id">二级地址ID</param>
    /// <returns></returns>
    public static string GetCounty(string token, string id)
    {
        CountyForJD model = new CountyForJD();
        List<CountyDetailsForJD> list = new List<CountyDetailsForJD>();
        //请求地址
        string url = string.Format("https://bizapi.jd.com/api/area/getCounty?token={0}&id={1}", token, id);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        JObject o = JObject.Parse(strMsg);
        if (Convert.ToBoolean(o["success"]))
        {
            //json序列化成字典
            Dictionary<string, object> dict = serializer.Deserialize<Dictionary<string, object>>(o["result"].ToString());
            foreach (string s in dict.Keys)
            {
                list.Add(new CountyDetailsForJD { countyId = Convert.ToInt32(dict[s]), countyName = s });
            }
        }
        model.resultCode = o["success"].ToString();
        model.resultMessage = o["resultMessage"].ToString();
        model.success = Convert.ToBoolean(o["success"]);
        model.result = list;
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 获取四级地址
    /// <summary>
    /// 获取四级地址
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="id">三级地址ID</param>
    /// <returns></returns>
    public static string GetTown(string token, string id)
    {
        TownForJD model = new TownForJD();
        List<TownDetailsForJD> list = new List<TownDetailsForJD>();
        //请求地址
        string url = string.Format("https://bizapi.jd.com/api/area/getTown?token={0}&id={1}", token, id);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        JObject o = JObject.Parse(strMsg);
        if (Convert.ToBoolean(o["success"]))
        {
            //json序列化成字典
            Dictionary<string, object> dict = serializer.Deserialize<Dictionary<string, object>>(o["result"].ToString());
            foreach (string s in dict.Keys)
            {
                list.Add(new TownDetailsForJD { townId = Convert.ToInt32(dict[s]), townName = s });
            }
        }
        model.resultCode = o["success"].ToString();
        model.resultMessage = o["resultMessage"].ToString();
        model.success = Convert.ToBoolean(o["success"]);
        model.result = list;
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 验证四级地址是否正确
    /// <summary>
    /// 验证四级地址是否正确
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="provinceId">省份ID</param>
    /// <param name="cityId">城市ID</param>
    /// <param name="countyId">县区ID</param>
    /// <param name="townId">乡镇ID</param>
    /// <returns></returns>
    public static string GetCheckArea(string token, string provinceId, string cityId, string countyId="0", string townId ="0")
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/area/checkArea";
        //请求形参集合
        List<string> ls = new List<string> { "token", "provinceId","cityId", "countyId", "townId" };
        //请求实参集合
        List<string> list = new List<string> { token,provinceId, cityId, countyId, townId };
        CheckAreaForJD model = DataInteractForJD.GetData<CheckAreaForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 校验某订单中某商品是否可以提交售后服务
    public static string GetAvailableNumberForJD(string token, string param)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/afterSale/getAvailableNumberComp";
        //请求形参集合
        List<string> ls = new List<string> { "token", "param" };
        //请求实参集合
        List<string> list = new List<string> { token, param };
        AvailableNumberForJD model = DataInteractForJD.GetData<AvailableNumberForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 根据订单号、商品编号查询支持的服务类型
    public static string GetCustomerExpectCompForJD(string token, string param)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/afterSale/getCustomerExpectComp";
        //请求形参集合
        List<string> ls = new List<string> { "token", "param" };
        //请求实参集合
        List<string> list = new List<string> { token, param };
        CustomerExpectCompForJD model = DataInteractForJD.GetData<CustomerExpectCompForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 根据订单号、商品编号查询支持的商品返回京东方式
    public static string GetWareReturnJdCompForJD(string token, string param)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/afterSale/getWareReturnJdComp";
        //请求形参集合
        List<string> ls = new List<string> { "token", "param" };
        //请求实参集合
        List<string> list = new List<string> { token, param };
        WareReturnJdCompForJD model = DataInteractForJD.GetData<WareReturnJdCompForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 根据客户账号和订单号分页查询服务单概要信息
    public static string GetServiceListPageForJD(string token, string param)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/afterSale/getServiceListPage";
        //请求形参集合
        List<string> ls = new List<string> { "token", "param" };
        //请求实参集合
        List<string> list = new List<string> { token, param };
        ServiceListPageForJD model = DataInteractForJD.GetData<ServiceListPageForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 根据服务单号查询服务单明细信息
    public static string GetServiceDetailInfoForJD(string token, string param)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/afterSale/getServiceDetailInfo";
        //请求形参集合
        List<string> ls = new List<string> { "token", "param" };
        //请求实参集合
        List<string> list = new List<string> { token, param };
        ServiceDetailInfoForJD model = DataInteractForJD.GetData<ServiceDetailInfoForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 取消服务单/客户放弃
    public static string GetAuditCancelForJD(string token, string param)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/afterSale/auditCancel";
        //请求形参集合
        List<string> ls = new List<string> { "token", "param" };
        //请求实参集合
        List<string> list = new List<string> { token, param };
        AuditCancelForJD model = DataInteractForJD.GetData<AuditCancelForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 发起支付接口
    /// <summary>
    /// 发起支付接口
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="jdOrderId">订单号</param>
    /// <returns></returns>
    public static string GetDoPay(string token,string jdOrderId)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/order/doPay";
        //请求形参集合
        List<string> ls = new List<string> { "token", "jdOrderId" };
        //请求实参集合
        List<string> list = new List<string> { token, jdOrderId };
        DoPayForJD model = DataInteractForJD.GetData<DoPayForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 统一余额查询接口
    /// <summary>
    /// 统一余额查询接口
    /// </summary>
    /// <param name="token">token码</param>
    /// <param name="payType">支付类型4：余额 7：网银钱包 101：金采支付</param>
    /// <returns></returns>
    public static string GetBalance(string token, string payType)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/price/getBalance";
        //请求形参集合
        List<string> ls = new List<string> { "token", "payType" };
        //请求实参集合
        List<string> list = new List<string> { token, payType };
        BalanceForJD model = DataInteractForJD.GetData<BalanceForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 统一下单接口
    /// <summary>
    /// 统一下单接口
    /// </summary>
    /// <param name="_model">参数实体</param>
    /// <returns></returns>
    public static string GetSubmitOrder(SubmitOrderParamForJD _model)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/order/submitOrder";
        //请求形参集合
        List<string> ls = new List<string> { "token", "thirdOrder", "sku", "name", "province", "city", "county", "town"
                                             , "address", "mobile", "email", "invoiceState", "invoiceType", "selectedInvoiceTitle", "companyName", "invoiceContent"
                                             , "paymentType", "isUseBalance", "submitState", "doOrderPriceMode", "orderPriceSnap"};
        //请求实参集合
        List<string> list = new List<string> { _model.token, _model.thirdOrder,_model.sku,_model.name,_model.province.ToString(),_model.city.ToString()
                                              ,_model.county.ToString(),_model.town.ToString(),_model.address,_model.mobile,_model.email,_model.invoiceState.ToString()
                                              ,_model.invoiceType.ToString(),_model.selectedInvoiceTitle.ToString(),_model.companyName,_model.invoiceContent.ToString()
                                              ,_model.paymentType.ToString(),_model.isUseBalance.ToString(),_model.submitState.ToString(),_model.doOrderPriceMode.ToString()
                                              ,_model.orderPriceSnap};
        if (!String.IsNullOrEmpty(_model.zip))
        {
            ls.Add("zip");
            list.Add(_model.zip);
        }
        if (!String.IsNullOrEmpty(_model.phone))
        {
            ls.Add("phone");
            list.Add(_model.phone);
        }
        if (!String.IsNullOrEmpty(_model.remark))
        {
            ls.Add("remark");
            list.Add(_model.remark);
        }
        //如果发票类型为增值税发票，同时开票方式为随货开票，那么以下值不能为空，如果不是则不考虑以下参数
        if (_model.invoiceType == 2 && _model.invoiceState == 1)
        {
            ls.Add("invoiceName");
            list.Add(_model.invoiceName);
            ls.Add("invoicePhone");
            list.Add(_model.invoicePhone);
            ls.Add("invoiceProvice");
            list.Add(_model.invoiceProvice.ToString());
            ls.Add("invoiceCity");
            list.Add(_model.invoiceCity.ToString());
            ls.Add("invoiceCounty");
            list.Add(_model.invoiceCounty.ToString());
            ls.Add("invoiceAddress");
            list.Add(_model.invoiceAddress);
        }
        ReturnSubmitOrderParamForJD model = DataInteractForJD.GetData<ReturnSubmitOrderParamForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 填写客户发运信息 未测试
    /// <summary>
    /// 填写客户发运信息
    /// </summary>
    /// <param name="afsServiceId">服务单号</param>
    /// <param name="freightMoney">运费</param>
    /// <param name="expressCompany">发运公司</param>
    /// <param name="deliverDate">发货日期</param>
    /// <param name="expressCode">货运单号</param>
    /// <returns></returns>
    public static string GetUpdateSendSku(string token, string afsServiceId,string freightMoney,string expressCompany,string deliverDate,string expressCode)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/afterSale/updateSendSku";
        //请求形参集合
        List<string> ls = new List<string> { "token", "afsServiceId","deliverDate", "expressCode","expressCompany", "freightMoney" };
        //请求实参集合
        List<string> list = new List<string> { token, afsServiceId, deliverDate, expressCode, expressCompany, freightMoney };
        UpdateSendSkuForJD model = DataInteractForJD.GetData<UpdateSendSkuForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region 服务单保存申请 未测试
    /// <summary>
    /// 服务单保存申请
    /// </summary>
    /// <param name="createModel">参数实体</param>
    /// <returns></returns>
    public static string GetCreateAfsApply(CreateAfsApplyForJD createModel)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/afterSale/createAfsApply";
        //请求形参集合
        List<string> ls = new List<string> { "param" };
        //请求实参集合
        List<string> list = new List<string> { JsonConvert.SerializeObject(createModel) };
        ReturnAfsApplyForJD model = DataInteractForJD.GetData<ReturnAfsApplyForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region  批量获取库存接口(建议商品列表页使用)
    public static string GetInventoryTwoForJD(string token, string sku, string area)
    {
        string url = string.Format("https://bizapi.jd.com/api/stock/getStockById?token={0}&sku={1}&area={2}", token, sku, area);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        JObject o = JObject.Parse(strMsg);
        //读取json:o节点下的result不规则json并转成为标准格式的json
        string json = "{result:" + o["result"].ToString().Replace(@"\", "") + "}";
        //序列为一个字典
        Dictionary<string, List<GetInventoryTwoJD>> ls = new JavaScriptSerializer().Deserialize<Dictionary<string, List<GetInventoryTwoJD>>>(json);

        InventoryTwoForJD model = new InventoryTwoForJD();
        model.success = Convert.ToBoolean(o["success"]);
        model.resultMessage = o["resultMessage"].ToString();
        model.resultCode = o["resultCode"].ToString();
        //读取key下的list集合
        model.result = ls["result"];
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region  批量获取库存接口（建议订单详情页、下单使用）
    public static string GetInventoryForJD(string token, string skuNums, string area)
    {
        string url = string.Format("https://bizapi.jd.com/api/stock/getNewStockById?token={0}&skuNums={1}&area={2}", token, skuNums, area);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        JObject o = JObject.Parse(strMsg);
        //读取json:o节点下的result不规则json并转成为标准格式的json
        string json = "{result:" + o["result"].ToString().Replace(@"\", "") + "}";
        //序列为一个字典
        Dictionary<string, List<GetInventoryJD>> ls = new JavaScriptSerializer().Deserialize<Dictionary<string, List<GetInventoryJD>>>(json);

        InventoryForJD model = new InventoryForJD();
        model.success = Convert.ToBoolean(o["success"]);
        model.resultMessage = o["resultMessage"].ToString();
        model.resultCode = o["resultCode"].ToString();
        //读取key下的list集合
        model.result = ls["result"];
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region  批量获取库存接口（买卖宝使用，以5为阈值）
    public static string GetInventoryThreeForJD(string token, string skuNums, string area)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/stock/getFiveStockById";
        //请求形参集合
        List<string> ls = new List<string> { "token", "skuNums", "area" };
        //请求实参集合
        List<string> list = new List<string> { token, skuNums, area };
        InventoryThreeForJD model = DataInteractForJD.GetData<InventoryThreeForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region  批量查询京东价价格
    public static string GetPriceForJD(string token, string sku)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/price/getJdPrice";
        //请求形参集合
        List<string> ls = new List<string> { "token", "sku" };
        //请求实参集合
        List<string> list = new List<string> { token, sku };
        PriceForJD model = DataInteractForJD.GetData<PriceForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region  批量查询协议价价格
    public static string GetAgreementPriceForJD(string token, string sku)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/price/getPrice";
        //请求形参集合
        List<string> ls = new List<string> { "token", "sku" };
        //请求实参集合
        List<string> list = new List<string> { token, sku };
        AgreementPriceForJD model = DataInteractForJD.GetData<AgreementPriceForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region  批量查询商品售卖价
    public static string GetSellingPriceForJD(string token, string sku)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/price/getSellPrice";
        //请求形参集合
        List<string> ls = new List<string> { "token", "sku" };
        //请求实参集合
        List<string> list = new List<string> { token, sku };
        SellingPriceForJD model = DataInteractForJD.GetData<SellingPriceForJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region  信息推送接口
    public static string GetInformationPushJD(string token)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/message/get";
        //请求形参集合
        List<string> ls = new List<string> { "token" };
        //请求实参集合
        List<string> list = new List<string> { token };
        InformationPushJD model = DataInteractForJD.GetData<InformationPushJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region  根据推送id，删除推送信息接口
    public static string Message_Del(string token, string id)
    {
        //请求地址
        string url = string.Format("https://bizapi.jd.com/api/message/del?token={0}&id={1}", token, id);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        return strMsg;
    }
    #endregion

    #region  取消未确认订单接口
    public static string cancel(string token, string jdOrderId)
    {
        //请求地址
        string url = string.Format("https://bizapi.jd.com/api/order/cancel?token={0}&jdOrderId={1}", token, jdOrderId);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        return strMsg;
    }
    #endregion

    #region  确认预占库存订单接口
    public static string confirmOrder(string token, string jdOrderId)
    {
        string url = string.Format("https://bizapi.jd.com/api/order/confirmOrder?token={0}&jdOrderId={1}", token, jdOrderId);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();
        return strMsg;
    }
    #endregion

    #region  余额明细查询接口
    public static string GetBalanceDetail(string token)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/price/getBalanceDetail";
        //请求形参集合
        List<string> ls = new List<string> { "token" };
        //请求实参集合
        List<string> list = new List<string> { token };
        GetBalanceDetailJD model = DataInteractForJD.GetData<GetBalanceDetailJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region  订单反查接口
    public static string GetSelectJdOrderIdByThirdOrder(string token, string thirdOrder)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/order/selectJdOrderIdByThirdOrder";
        //请求形参集合
        List<string> ls = new List<string> { "token", "thirdOrder" };
        //请求实参集合
        List<string> list = new List<string> { token, thirdOrder };
        SelectJdOrderIdByThirdOrder model = DataInteractForJD.GetData<SelectJdOrderIdByThirdOrder>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region  查询配送信息接口
    public static string GetOrderTrack(string token, string jdOrderId)
    {
        //请求地址
        string url = "https://bizapi.jd.com/api/order/orderTrack";
        //请求形参集合
        List<string> ls = new List<string> { "token", "jdOrderId" };
        //请求实参集合
        List<string> list = new List<string> { token, jdOrderId };
        OrderTrackJD model = DataInteractForJD.GetData<OrderTrackJD>(url, ls, list);
        return JsonConvert.SerializeObject(model);
    }
    #endregion

    #region  查询京东订单信息接口(未测试)
    public static string GetSelectJdOrder(string token, string jdOrderId)
    {
        JavaScriptSerializer jsonReader = new JavaScriptSerializer();
        object[] obj = new object[2];
        //请求地址
        string url = string.Format("https://bizapi.jd.com/api/order/selectJdOrder?token={0}&jdOrderId={1}", token, jdOrderId);
        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
        string strMsg = reader.ReadToEnd();

        JObject o = JObject.Parse(strMsg);
        if (o["result"]["pOrder"].ToString() == "0")
        {
            obj[0] = 0;
            obj[1] = jsonReader.Deserialize<SelectJdOrderJDTwo>(strMsg);

        }
        else
        {
            obj[0] = 1;
            obj[1] = jsonReader.Deserialize<SelectJdOrderJD>(strMsg);
        }
        return JsonConvert.SerializeObject(obj[1]);

    }
    #endregion

    //电商ID
    private static string EBusinessID = "1279573";
    //电商加密私钥，快递鸟提供，注意保管，不要泄漏
    private static string AppKey = "d905b29d-d170-4eaf-9b81-cea506d2bf52";
    //请求url
    private static string ReqURL = "http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx";
    /// <summary>
    /// Json方式 查询订单物流轨迹
    /// </summary>
    /// <param name="OrderCode">订单编号</param>
    /// <param name="ShipperCode">快递公司编码</param>
    /// <param name="LogisticCode">物流单号</param>
    /// <returns></returns>
    public static string getOrderTracesByJson(string OrderCode,string ShipperCode,string LogisticCode)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        Dictionary<string, object> list = new Dictionary<string, object>();
        list.Add("OrderCode", string.IsNullOrEmpty(OrderCode)?"": OrderCode);
        list.Add("ShipperCode", ShipperCode);
        list.Add("LogisticCode", LogisticCode);
        string requestData = jss.Serialize(list);

        Dictionary<string, string> param = new Dictionary<string, string>();
        param.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8));
        param.Add("EBusinessID", EBusinessID);
        param.Add("RequestType", "1002");
        string dataSign = encrypt(requestData, AppKey, "UTF-8");
        param.Add("DataSign", HttpUtility.UrlEncode(dataSign, Encoding.UTF8));
        param.Add("DataType", "2");
        string result = sendPost(ReqURL, param);
        return result;
    }
    /// <summary>
    /// Post方式提交数据，返回网页的源代码
    /// </summary>
    /// <param name="url">发送请求的 URL</param>
    /// <param name="param">请求的参数集合</param>
    /// <returns>远程资源的响应结果</returns>
    private static string sendPost(string url, Dictionary<string, string> param)
    {
        string result = "";
        StringBuilder postData = new StringBuilder();
        if (param != null && param.Count > 0)
        {
            foreach (var p in param)
            {
                if (postData.Length > 0)
                {
                    postData.Append("&");
                }
                postData.Append(p.Key);
                postData.Append("=");
                postData.Append(p.Value);
            }
        }
        byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(postData.ToString());
        try
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Referer = url;
            request.Accept = "*/*";
            request.Timeout = 30 * 1000;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
            request.Method = "POST";
            request.ContentLength = byteData.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(byteData, 0, byteData.Length);
            stream.Flush();
            stream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream backStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(backStream, Encoding.GetEncoding("UTF-8"));
            result = sr.ReadToEnd();
            sr.Close();
            backStream.Close();
            response.Close();
            request.Abort();
        }
        catch (Exception ex)
        {
            result = ex.Message;
        }
        return result;
    }
    ///<summary>
    ///电商Sign签名
    ///</summary>
    ///<param name="content">内容</param>
    ///<param name="keyValue">Appkey</param>
    ///<param name="charset">URL编码 </param>
    ///<returns>DataSign签名</returns>
    private static string encrypt(String content, String keyValue, String charset)
    {
        if (keyValue != null)
        {
            return base64(MD5(content + keyValue, charset), charset);
        }
        return base64(MD5(content, charset), charset);
    }
    ///<summary>
    /// 字符串MD5加密
    ///</summary>
    ///<param name="str">要加密的字符串</param>
    ///<param name="charset">编码方式</param>
    ///<returns>密文</returns>
    private static string MD5(string str, string charset)
    {
        byte[] buffer = System.Text.Encoding.GetEncoding(charset).GetBytes(str);
        try
        {
            System.Security.Cryptography.MD5CryptoServiceProvider check;
            check = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] somme = check.ComputeHash(buffer);
            string ret = "";
            foreach (byte a in somme)
            {
                if (a < 16)
                    ret += "0" + a.ToString("X");
                else
                    ret += a.ToString("X");
            }
            return ret.ToLower();
        }
        catch
        {
            throw;
        }
    }

    /// <summary>
    /// base64编码
    /// </summary>
    /// <param name="str">内容</param>
    /// <param name="charset">编码方式</param>
    /// <returns></returns>
    private static string base64(String str, String charset)
    {
        return Convert.ToBase64String(System.Text.Encoding.GetEncoding(charset).GetBytes(str));
    }
    /// <summary>
    /// 返回提示信息
    /// </summary>
    /// <param name="exMessage"></param>
    /// <param name="isTrue"></param>
    /// <returns></returns>
    public static string JsonErrorMessage(string exMessage, string isTrue)
    {
        return string.Format("{{\"Result\":" + isTrue + ",\"Message\":\"{0}\"}}", new System.Text.RegularExpressions.Regex("\\n|\\r|\\(|\\)| |\"|\\\\").Replace(exMessage, ""));
    }
}